package com.bookkeeping.cn;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bookkeeping.cn.databinding.ActivityBookKeepBinding;
import com.bookkeeping.cn.model.BookKeepDto;
import com.bookkeeping.cn.model.BookKeepReturnDto;
import com.bookkeeping.cn.ui.home.HomeFragment;
import com.bookkeeping.cn.util.Base64Util;
import com.bookkeeping.cn.util.OkHttpUtil;
import com.bookkeeping.cn.util.URLUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BookKeepActivity extends AppCompatActivity {
    private ActivityBookKeepBinding binding;

    Integer year, month, day;
    DatePickerDialog dlg;

    TextView dateTv;
    RadioGroup typeRg;
    Integer type = 1; // 1:收入 0:支出
    EditText categoryEt;
    EditText priceEt;
    EditText remarkEt;
    Button addBt;

    TextView backText;

    ImageView back;

    Integer bookKeepId;

    RadioButton sumRb,useRb;

    Button recognizeBt;

    String baiduAccessToke;
    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;

    // 检查是否已经同意了查看相册权限
    private boolean checkGalleryPermission() {
        int ret = ActivityCompat.checkSelfPermission(BookKeepActivity.this,
                Manifest.permission.READ_MEDIA_IMAGES);
        if (ret != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(BookKeepActivity.this,
                    new String[]{Manifest.permission.READ_MEDIA_IMAGES},
                    1000);
            return false;
        }
        return true;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBookKeepBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 绑定控件
        dateTv = findViewById(R.id.date_tv);
        categoryEt = findViewById(R.id.category_et);
        priceEt = findViewById(R.id.price_et);
        remarkEt = findViewById(R.id.remark_et);
        addBt = findViewById(R.id.add_bt);
        typeRg = findViewById(R.id.type_rg);
        backText=findViewById(R.id.back_text);
        back=findViewById(R.id.back);
        sumRb=findViewById(R.id.sum_rb);
        useRb=findViewById((R.id.use_rb));
        recognizeBt=findViewById(R.id.recognize_button);
        recognizeBt.setOnClickListener(x -> {
            if (checkGalleryPermission()) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_FRONT);
            }
        });
        // 设置添加按钮点击事件
        addBt.setOnClickListener(v -> submit());

        backText.setOnClickListener(x->{
            startActivity(new Intent(this,MainActivity.class));
            finish();
        });
        back.setOnClickListener(x->{
            startActivity(new Intent(this, MainActivity.class));
            finish();
        });

        // 设置类型选择监听
        typeRg.setOnCheckedChangeListener((radioGroup, checkedId) -> {
            if (checkedId == R.id.sum_rb) {
                type = 1; // 收入
            } else if (checkedId == R.id.use_rb) {
                type = 0; // 支出
            }
        });

        // 初始化日期
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);

        updateDateText();

        // 设置日期点击事件，显示日历选择器
        dateTv.setOnClickListener(v -> dlg.show());

        // 初始化日期选择器
        dlg = new DatePickerDialog(
                new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar),
                (datePicker, yearSelected, monthSelected, daySelected) -> {
                    year = yearSelected;
                    month = monthSelected + 1;
                    day = daySelected;
                    updateDateText();
                }, year, month - 1, day);

        //获取页面传参
        bookKeepId=getIntent().getIntExtra("bookKeepId",0);
        if(bookKeepId!=0)
        {
            //点击编辑按钮
            addBt.setText("编辑");
            //根据id获取详情将参数填充到编辑页面中
            getDetailById();
        }
        getBaiduAcessToken();
    }

    //根据id获取账单详情
    private void getDetailById() {

        Request request=new Request.Builder().url(URLUtil.GET_BOOK_KEEP+"/"+bookKeepId).get().addHeader("Authorization",URLUtil.TOKEN).build();
        OkHttpUtil.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str=response.body().string();
                JSONObject jsonObject=JSON.parseObject(str);
                BookKeepDto dto=JSON.parseObject(jsonObject.getString("content"), BookKeepDto.class);

                //将接口返回的数据填充在页面的元素中
                runOnUiThread(()->{
                  //先设置记账日期
                    String[] split=dto.getBookKeepDate().split("-");
                    year=Integer.parseInt(split[0]);
                    month=Integer.parseInt(split[1]);
                    day=Integer.parseInt(split[2]);
                    updateDateText();
                    //设置记账类型
                    if(dto.getType().equals(0)){
                        useRb.setChecked(true);
                    }else {
                        sumRb.setChecked(true);
                    }

                    //设置分类、金额、备注
                    categoryEt.setText(dto.getCategory());
                    priceEt.setText(dto.getPrice().toString());
                    if(dto.getRemark()!=null)
                    {
                        remarkEt.setText(dto.getRemark());
                    }
                });
                runOnUiThread(()->{
                    Toast.makeText(BookKeepActivity.this,jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                });

            }
        });
    }

    private void updateDateText() {
        String dateText = "记账日期:" + year + "年" + month + "月" + day + "日";
        dateTv.setText(dateText);
    }

    public void submit() {
        // 检查必填项
        if (isEmpty(categoryEt)) {
            showToast("分类必须填写");
            return;
        }
        if (isEmpty(priceEt)) {
            showToast("金额必须填写");
            return;
        }

        // 构建请求数据
        JSONObject jsonObject = new JSONObject();
        String formattedDate = String.format("%d-%02d-%02d", year, month, day);
        jsonObject.put("bookKeepDate", formattedDate);
        jsonObject.put("type", type);
        jsonObject.put("cagegory", categoryEt.getText().toString()); // 修正拼写错误：cagegory -> category
        jsonObject.put("price", priceEt.getText().toString());
        jsonObject.put("remark", remarkEt.getText().toString());

        // 构建请求
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json;charset=utf-8"),
                jsonObject.toJSONString()
        );

        // 检查URL和TOKEN是否为空
        if (URLUtil.ADD_BOOK_KEEP == null || URLUtil.TOKEN == null) {
            showToast("网络请求配置错误");
            return;
        }

        Request request ;
        if(bookKeepId==0)
        {
            request= new Request.Builder()
                    .url(URLUtil.ADD_BOOK_KEEP)
                    .post(requestBody)
                    .addHeader("Authorization", URLUtil.TOKEN)
                    .build();
        }else{
            request= new Request.Builder()
                    .url(URLUtil.ADD_BOOK_KEEP+"/"+bookKeepId)
                    .put(requestBody)
                    .addHeader("Authorization", URLUtil.TOKEN)
                    .build();
        }
        // 发送请求
        OkHttpUtil.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> showToast("网络请求失败: " + e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String str = response.body().string();
                    JSONObject jsonObjectResponse = JSON.parseObject(str);

                    if (jsonObjectResponse.getInteger("code") == -9) {
                        logout();
                    }

                    runOnUiThread(() -> showToast(jsonObjectResponse.getString("message")));
                } catch (Exception e) {
                    runOnUiThread(() -> showToast("解析响应失败: " + e.getMessage()));
                }
            }
        });
    }

    private void logout() {
        SharedPreferences.Editor editor = getSharedPreferences("token_file", Context.MODE_PRIVATE).edit();
        editor.remove("token");
        editor.apply();
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    // 辅助方法：检查EditText是否为空
    private boolean isEmpty(EditText editText) {
        return editText.getText().toString().trim().isEmpty();
    }

    // 辅助方法：显示Toast
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            //下一步直接调用百度接口
            baduiOCR(filePath);
        }
    }
    //获取选择的文件的真实路径
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }
    public void getBaiduAcessToken(){
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=").append(URLUtil.BAIDU_API_KEY).append("&client_secret=").append(URLUtil.BAIDU_SECRET_KEY);
        Request request=new Request.Builder().url(stringBuffer.toString()).get().build();
        OkHttpUtil.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str=response.body().string();
                JSONObject jsonObject=JSON.parseObject(str);
                baiduAccessToke=jsonObject.getString("access_token");
            }
        });
    }
    public void baduiOCR(String filePath){

        //先将filePath路径获取到文件字节，将字节进行base64加密
        byte[] bytes=Base64Util.reaFileFromSDcard(filePath);
        try {
            String s=Base64Util.byte2String(bytes);
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=").append(baiduAccessToke);

            RequestBody requestBody=RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),"image="+s);
            Request request=new Request.Builder().url(stringBuffer.toString()).post(requestBody).build();
            OkHttpUtil.getInstance().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //百度ocr成功回调接口
                    String str =response.body().string();
                    JSONObject jsonObject=JSON.parseObject(str);
                    JSONArray wordResult=jsonObject.getJSONArray("words_result");

                    runOnUiThread(()->{
                        int i=0;
                        for(i=0;i<wordResult.size();i++) {
                            JSONObject itemJson = wordResult.getJSONObject(i);
                            if (itemJson.getString("words").equals("支付时间")) {
                                JSONObject dateJson = wordResult.getJSONObject(++i);
                                String dateStr = dateJson.getString("words").substring(0, 10);
                                String[] split = dateStr.split("-");
                                year = Integer.parseInt(split[0]);
                                month = Integer.parseInt(split[1]);
                                day = Integer.parseInt(split[2]);
                                updateDateText();
                                continue;
                            }
                            if(itemJson.getString("words").equals("交易成功"))
                            {
                                JSONObject dataJson =wordResult.getJSONObject(i-1);
                                String priceStr =dataJson.getString("words");
                                // 判断价格字符串前缀，设置 RadioButton 选中状态
                                if (priceStr.substring(0,1).equals("-")) {
                                    useRb.setChecked(true); // 支出
                                } else {
                                    sumRb.setChecked(true); // 收入
                                }
                                 // 截取价格字符串并设置到 EditText
                                priceEt.setText(priceStr.substring(1));
                                continue;
                            }
                            if(itemJson.getString("words").equals("账单分类"))
                            {
                                JSONObject dataJson =wordResult.getJSONObject(i+1);
                                categoryEt.setText(dataJson.getString("words").substring(0,dataJson.getString("words").length()-1));

                            }
                        }
                    });
                }
            });
        } catch (Exception e) {
            System.out.println("错误信息"+e.getMessage());
        }
    }
}